package com.jboost.modules.app.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jboost.common.api.vo.Result;
import com.jboost.common.constant.enums.OpEnum;
import com.jboost.common.util.HttpRestUtils;
import com.jboost.modules.app.constant.CompanyApiKeyEnum;
import com.jboost.modules.app.constant.CompanyEnum;
import com.jboost.modules.app.util.EnumUtils;
import com.jboost.modules.system.constant.ConnectEnum;
import com.jboost.modules.system.constant.DepartEnum;
import com.jboost.modules.system.entity.SysUser;
import com.jboost.modules.system.mapper.SysUserMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
@Component
public class AppBaseController {

    @Autowired
    SysUserMapper sysUserMapper;
    final static Map<String,String> cache = new HashMap<>();
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

    public String getUserId() {
        return "1604487947082588162";
    }

    public HttpHeaders getApiKeyHeaders(String type) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + ((CompanyEnum)EnumUtils.getEnumByType(CompanyEnum.class,type)).getApiKey());
        return headers;
    }
    @SneakyThrows
    public String getDepartNoByName(String departName, String company){
        Map<String,Object> map = new HashMap<>();
        map.put("dept_no",1);
        map.put("has_child",true);
        String post = HttpRestUtils.post(DepartEnum.GET.getUrl(), map,getApiKeyHeaders(company));
        LinkedHashMap linkedHashMap = JSONObject.parseObject(post, LinkedHashMap.class);
        JSONArray departments = (JSONArray)linkedHashMap.get("departments");
        for (Object department : departments) {
            JSONObject jsonObject = (JSONObject)department;
            String name = jsonObject.getString("name");
            if (Objects.equals(name,departName)){
                return jsonObject.getString("dept_no");
            }
        }
        return null;
    }
    public Result<String> pushResult(JSONObject jsonObject) throws IOException {
        String op = jsonObject.getString("op");

        LinkedHashMap data = (LinkedHashMap) jsonObject.get("data");
        //应用id
        String appId = (String)data.get("appId");
        String depart = getDepartNoByName((String) data.get("depart"),appId);
        if (Objects.equals(op, OpEnum.DATA_CREATE.getOp())){
            SysUser sysUser = new SysUser();
            sysUser.setClientId((String) data.get("_id"));
            sysUser.setUsername((String) data.get("username"));
            sysUser.setRealname((String) data.get("account"));
//            sysUser.setPhone((String) data.get("phone"));
            sysUser.setPassword((String) data.get("password"));
            sysUser.setThirdId(appId);
            sysUser.setDelFlag(0);
            sysUser.setDepartIds(depart);
            sysUser.setCreateBy(appId);
            sysUserMapper.insert(sysUser);
            Map<String,Object> map = new HashMap<>();
            map.put("username",sysUser.getRealname());
            map.put("name",sysUser.getUsername());
            map.put("departments",Arrays.asList(sysUser.getDepartIds()));
            HttpRestUtils.post(ConnectEnum.ADD.getUrl(), map,getApiKeyHeaders(appId));
        }
        if (Objects.equals(op,OpEnum.DATA_UPDATE.getOp())){
            SysUser userByName = sysUserMapper.selectOneByClientId((String) data.get("_id"));
            if (Objects.isNull(userByName)){
                userByName = new SysUser();
                userByName.setDelFlag(0);
                userByName.setDepartIds(depart);
                userByName.setUsername((String) data.get("username"));
                userByName.setRealname((String) data.get("account"));
                userByName.setPassword((String) data.get("password"));
                userByName.setClientId((String) data.get("_id"));
                sysUserMapper.insert(userByName);
                Map<String,Object> map = new HashMap<>();
                map.put("username",userByName.getRealname());
                map.put("name",userByName.getUsername());
                map.put("departments",Arrays.asList(userByName.getDepartIds()));
                HttpRestUtils.post(ConnectEnum.ADD.getUrl(), map,getApiKeyHeaders(appId));
            }else {
                userByName.setPassword((String) data.get("password"));
                userByName.setUsername((String) data.get("username"));
                userByName.setDepartIds(depart);
                userByName.setClientId((String) data.get("_id"));
                sysUserMapper.updateById(userByName);
                Map<String,Object> map = new HashMap<>();
                map.put("username",userByName.getRealname());
                map.put("name",userByName.getUsername());
                map.put("departments",Arrays.asList(userByName.getDepartIds()));
                HttpRestUtils.post(ConnectEnum.UPDATE.getUrl(), map,getApiKeyHeaders(appId));
            }
        }
        if (Objects.equals(op,OpEnum.DATA_REMOVE.getOp())){
            SysUser sysUser = new SysUser();
            sysUser.setUsername((String) data.get("username"));
            SysUser userByName = sysUserMapper.selectOneByClientId((String) data.get("_id"));
            if (Objects.nonNull(userByName)) {
                sysUserMapper.deleteWithId(userByName.getId());
                Map<String,Object> map = new HashMap<>();
                map.put("username",userByName.getRealname());
                HttpRestUtils.post(ConnectEnum.DELETE.getUrl(), map,getApiKeyHeaders(appId));
            }
        }
        System.out.println(jsonObject);
        return Result.OK();
    }

    public Result<String> getStringResult(JSONObject jsonObject, String op) throws IOException {
        LinkedHashMap data = (LinkedHashMap) jsonObject.get("data");
        //应用id
        String appId = (String)data.get("appId");
        Map<String,Object> map = new HashMap<>();
        if (Objects.equals(op,OpEnum.DATA_CREATE.getOp())){
            map.put("name",(String) data.get("name"));
            map.put("parent_no", data.get("parent_no"));
            map.put("dept_no", data.get("dept_no"));
            String post = HttpRestUtils.post(DepartEnum.ADD.getUrl(), map, getApiKeyHeaders(appId));
            cache.put((String) data.get("_id"),(String) data.get("dept_no"));
        }
        if (Objects.equals(op,OpEnum.DATA_UPDATE.getOp())){
            map.put("name",(String) data.get("name"));
            map.put("parent_no", data.get("parent_no"));
            map.put("dept_no", data.get("dept_no"));
            HttpRestUtils.post(DepartEnum.UPDATE.getUrl(), map,getApiKeyHeaders(appId));
            cache.put((String) data.get("_id"),(String) data.get("dept_no"));
        }
        if (Objects.equals(op,OpEnum.DATA_REMOVE.getOp())){
            map.put("dept_no",cache.get((String) data.get("_id")));
            HttpRestUtils.post(DepartEnum.DELETE.getUrl(), map,getApiKeyHeaders(appId));
        }
        System.out.println(jsonObject);
        return Result.OK();
    }


}
